package com.baymax.study.tuLing.netty.d1_base;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author baymax
 * @since 2025-07-01
 */
@Slf4j
public class Demo4_Echo {
    public static final int PORT = 60001;

    static class EchoServer {
        public static void main(String[] args) throws InterruptedException {
            ChannelFuture future = new ServerBootstrap().group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8))
                            //.addLast(new StringEncoder(StandardCharsets.UTF_8))
                            .addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    log.info("EchoServer Received: {}", msg);
                                    ctx.writeAndFlush(Unpooled.copiedBuffer(msg, StandardCharsets.UTF_8));
                                }
                            });
                    }
                })
                .bind(new InetSocketAddress(PORT))
                .sync();
            log.info("EchoServer started");
            future.channel().closeFuture().sync();
        }
    }

    static class EchoClient {
        public static void main(String[] args) throws InterruptedException {
            NioEventLoopGroup group = new NioEventLoopGroup();
            ChannelFuture channelFuture = new Bootstrap().group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                            .addLast(new StringEncoder(StandardCharsets.UTF_8))
                            .addLast(new SimpleChannelInboundHandler<Object>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf buf = (ByteBuf) msg;
                                    log.info("EchoClient Received: {}", buf.toString(StandardCharsets.UTF_8));
                                }
                            });
                    }
                })
                .connect(new InetSocketAddress("127.0.0.1", PORT))
                .sync();
            log.info("EchoClient started");
            try {
                Channel channel = channelFuture.channel();
                log.info("请输入，输入q!退出");
                while (true) {
                    Scanner scanner = new Scanner(System.in);
                    String line = scanner.nextLine();
                    if ("q!".equals(line)) {
                        channel.close();
                        break;
                    }
                    channel.writeAndFlush(line);
                }
                channel.closeFuture().sync();
            } finally {
                group.shutdownGracefully();
                log.info("EchoClient closed");
            }
        }
    }
}
